package com.gdut.demo.message;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
//import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 *  该类用于后台主动发送http请求
 *  url属性指定发送url
 *  map属性指定发送的json数据
 *  文件发送未是实现
 */
public class SendHttpRequest {

    private String url;
    private Map<String,Object> map;
    private String filePath;

    private ArrayList<Integer> eegList;

    private void generateList(){
        for(Integer i=0;i<150000;i++){
            eegList.set(i, 2000);
        }
    }

    public SendHttpRequest(String url, Map<String, Object> map) {
        this.url = url;
        this.map = map;
    }

    public SendHttpRequest(String url, Map<String, Object> map,String filePath) {
        this.url = url;
        this.map = map;
        this.filePath = filePath;
    }

    public SendHttpRequest() {
    }

    /**
     * 该方法用于后台主动发送http请求，post类型
     */
    public void doPostTest() {

        Map<String,Object> maptest = new HashMap<String, Object>();
        maptest.put("user","yu");
        maptest.put("fileExist",true);
        maptest.put("algorithm","1");
        maptest.put("info","2");

//        JSONObject mapJSON = new JSONObject(maptest);
        JSONObject mapJSON = new JSONObject(maptest);

        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(1000).build();
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        //CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultSocketConfig(socketConfig).build();

        // 创建Post请求
        //HttpPost httpPost = new HttpPost(url);
        HttpPost httpPost = new HttpPost("http://localhost:8888/upload");
        //StringEntity entity = new StringEntity(mapJSON.toString(), "UTF-8");
//        File file = new File("C:/User/12865/Desktop/uploadtest.txt");
        File file = new File(filePath);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //设置浏览器兼容模式
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        //设置请求的编码格式
        builder.setCharset(Consts.UTF_8);

        //添加文件
        builder.setContentType(ContentType.MULTIPART_FORM_DATA);
        builder.addBinaryBody("uploadFile", file,ContentType.MULTIPART_FORM_DATA,file.getName());
        //添加字段
//        StringBody body = new StringBody("yu",ContentType.TEXT_PLAIN);
//        builder.addPart("serverPart",body);
        builder.addTextBody("userDescription",mapJSON.toString(),ContentType.create("application/json", StandardCharsets.UTF_8));
        HttpEntity entity = builder.build();
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(entity);


        //httpPost.setHeader("Content-Type", "multipart/form-data;application/json;charset=utf8");

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Post请求

            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000)
                    .setConnectTimeout(2000)
                    .build();
            // 从响应模型中获取响应实体
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
